package com.yj.auto.component.base.controller;

import java.util.List;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.yj.auto.Constants;
import com.yj.auto.component.base.model.Msg;
import com.yj.auto.component.base.model.MsgBox;
import com.yj.auto.component.base.model.validator.MsgDraftGroup;
import com.yj.auto.component.base.model.validator.MsgSentGroup;
import com.yj.auto.component.base.service.MsgService;
import com.yj.auto.core.base.annotation.Controller;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.base.model.ResponseModel;
import com.yj.auto.core.base.model.ValidResult;
import com.yj.auto.core.jfinal.base.BaseController;
import com.yj.auto.core.jfinal.interceptor.ValidatorInterceptor;
import com.yj.auto.core.web.system.model.User;
import com.yj.auto.helper.AutoHelper;
import com.yj.auto.plugin.table.model.DataTables;

/**
 * 系统消息 管理
 * 
 * 描述：
 * 
 */
@Controller(viewPath = "component/base")
public class MsgController extends BaseController {
	private static final Log logger = Log.getLog(MsgController.class);

	private static final String RESOURCE_URI = "msg/index";
	private static final String INDEX_PAGE = "msg_index.html";
	private static final String FORM_PAGE = "msg_form.html";
	private static final String SHOW_PAGE = "msg_show.html";

	MsgService msgSrv = null;

	public void box() {
		QueryModel query = new QueryModel();
		// query.setStime(DateUtil.toDateStr(DateUtil.addDay(DateUtil.date(), -7)));
		query.setType(getPara(0, MsgBox.BOX_TYPE_INBOX));
		setAttr("query", query);
		render(INDEX_PAGE);
	}

	public void list(QueryModel query) {
		query.setUserId(getSuId());
		DataTables<Msg> dt = getDataTable(query, msgSrv);
		renderJson(dt);
	}

	// 首页展示未读的邮件
	public void portlet() {
		QueryModel query = new QueryModel();
		query.setUserId(getSuId());
		query.setType(MsgBox.BOX_TYPE_INBOX);
		query.put("unread", true);
		Page<Msg> page = msgSrv.paginate(query);
		renderJson(page);
	}

	public void get() {
		Integer id = getParaToInt(0);
		Msg model = msgSrv.get(id);
		msgSrv.updateUserReadTime(id, getSuId());
		User user = AutoHelper.getUserService().get(model.getFromId());
		if (null != user) {
			model.put("from_name", user.getName());
		}
		setAttr("model", model);
		render(SHOW_PAGE);
	}

	// 新建
	public void add() {
		getMsg(null);
	}

	// 编辑(草稿箱)
	public void edit() {
		getMsg("draft");
	}

	// 回复
	public void reply() {
		getMsg("reply");
	}

	// 转发
	public void forward() {
		getMsg("forward");
	}

	private void getMsg(String action) {
		Integer id = getParaToInt(0);
		Msg model = null;
		if (null != id && 0 != id) {
			model = msgSrv.get(id);
			if (null != model) {
				if (!MsgService.ACTION_DRAFT.equals(action)) {
					model.setId(null);// 如果不是草稿箱中编辑邮件,ID设置为空
				}
				if ("reply".equals(action)) {
					model.setSubject("回复：" + model.getSubject());
					model.setToId("U" + model.getFromId());
					User user = AutoHelper.getUserService().get(model.getFromId());
					if (null != user) {
						model.setToName(user.getName());
					}
					model.setCcId(null);
					model.setCcName(null);
				} else if ("forward".equals(action)) {// 不包括附件
					model.setSubject("转发：" + model.getSubject());
					model.setToId(null);
					model.setToName(null);
					model.setCcId(null);
					model.setCcName(null);
				}
			}
		} else {
			model = new Msg();
		}
		setAttr("model", model);
		render(FORM_PAGE);
	}

	public boolean saveOrUpdate(Msg model) {
		boolean success = false;
		model.put("action", getPara("msg_action", MsgService.ACTION_SENT));
		Class<?>[] groups = null;
		if (MsgService.ACTION_SENT.equals(model.get("action"))) {// 立即发送
			groups = new Class<?>[] { MsgSentGroup.class, MsgDraftGroup.class };
		} else {
			groups = new Class<?>[] { MsgDraftGroup.class };
		}
		List<ValidResult> error = ValidatorInterceptor.me().validate(model, groups, "model");
		if (error.size() > 0) {
			ResponseModel<List<ValidResult>> res = new ResponseModel<List<ValidResult>>(false);
			res.setData(error);
			renderJson(res);
			logger.warn("系统消息验证失败");
			return false;
		}
		model.setCtime(Constants.NOW());
		model.setFromId(getSuId());
		this.initAttaMap(model, MsgService.ATTA_MSG);
		if (null == model.getId()) {
			success = msgSrv.save(model);
		} else {
			success = msgSrv.update(model);
		}
		ResponseModel<String> res = renderSaveOrUpdate(success, msgSrv);
		return res.isSuccess();
	}

	public boolean delete() {
		Integer[] ids = getParaValuesToInt();
		String boxType = getPara("type");
		boolean success = msgSrv.deleteBox(getSuId(), boxType, ids);
		ResponseModel<String> res = new ResponseModel<String>(success);
		res.setMsg("选中" + msgSrv.getDao().getTableRemark() + "删除" + (res.isSuccess() ? "成功" : "失败"));
		renderJson(res);
		return success;
	}
}